package com.scx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scx.constant.RedisConstants;
import com.scx.context.BaseContext;
import com.scx.dto.ScrollResult;
import com.scx.entity.Blog;
import com.scx.entity.Follow;
import com.scx.entity.User;
import com.scx.mapper.BlogMapper;
import com.scx.result.Result;
import com.scx.service.BlogService;
import com.scx.service.FollowService;
import com.scx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.error("笔记不存在");
        }
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.success(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = BaseContext.getCurrentId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //判断当前用户是否已点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            boolean upd = update().setSql("liked = liked - 1").eq("id", id).update();
            if (upd) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else {
            boolean upd = update().setSql("liked = liked + 1").eq("id", id).update();
            if (upd) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.success();
    }

    @Override
    public Result queryLikesById(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
//        根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<User> userDTOList = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")")
                .list().stream().map(user -> BeanUtil.copyProperties(user, User.class))
                .collect(Collectors.toList());
        return Result.success(userDTOList);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, 10));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });
        return Result.success(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        blog.setUserId(BaseContext.getCurrentId());
        boolean saved = save(blog);
        if (!saved) {
            return Result.error("发布失败");
        }
        //获取粉丝列表
        List<Follow> followList = followService.query().select("user_id").eq("follow_user_id", BaseContext.getCurrentId()).list();
        for (Follow follow : followList) {
            //粉丝的id
            Long userId = follow.getUserId();
            String key = RedisConstants.FEED_KEY + userId;
            //将作品id推送给所有粉丝
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.success(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Long offset) {
        Long userId = BaseContext.getCurrentId();
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.success();
        }
        // 解析数据：blogId、minTime（时间戳）、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        //相同意味着本次分页的所有时间戳都一样，没有时间变化
        os = minTime == max ? (int) (os + offset) : os;
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }

        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.success(r);
    }

    private void queryBlogUser(Blog blog) {
        User user = userService.getById(blog.getUserId());
        blog.setIcon(user.getAvatar());
        blog.setName(user.getName());
    }

    private void isBlogLiked(Blog blog) {
        Long userId = BaseContext.getCurrentId();
        // 判断当前登录用户是否已经点赞
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
}
